<template>
  <div>
    <van-search
      v-model="searchValue"
      placeholder="请输入搜索关键词"
      shape="round"
    />

    <!-- 搜索下容器 -->
    <div class="search_wrap" v-if="resultList.length === 0">
      <!-- 标题 -->
      <p class="hot_title">热门搜索</p>
      <!-- 热搜关键词容器 -->
      <div class="hot_name_wrap">
        <!-- 每个搜索关键词 -->
        <span
          class="hot_item"
          v-for="(obj, index) in hotList"
          :key="index"
          @click="btn(obj.first)"
          >{{ obj.first }}</span
        >
      </div>
      <!-- 历史记录 -->
      <van-cell
        class="hot_title"
        title="历史记录"
        v-show="searchHistory.length"
      >
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete-o" @click="clearBtn" class="delete-icon" />
        </template>
      </van-cell>
      <!-- 历史记录容器 -->
      <div class="hot_name_wrap" v-show="searchHistory.length">
        <!-- 搜索记录关键词 -->
        <span
          class="hot_item searchKeyWork"
          v-for="(val, index) in searchHistory"
          :key="index"
          @click="btn(val)"
          >{{ val
          }}<van-icon
            name="close"
            @click.stop="delBtn(index)"
            class="delectico"
        /></span>
      </div>
    </div>
    <!-- 搜索结果 -->
    <div class="search_wrap" v-else>
      <!-- 标题 -->
      <p class="hot_title">最佳匹配</p>
      <!-- 使用封装的组件 -->
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <SongItem
          v-for="obj in resultList"
          :key="obj.id"
          :name="obj.name"
          :author="obj.ar[0].name"
          :id="obj.id"
        ></SongItem>
      </van-list>
    </div>
  </div>
</template>

<script>
import { onMounted, ref, watchEffect } from "vue";
import { useStore } from "vuex";
import debounce from "lodash/debounce"; //防抖
import SongItem from "@/components/SongItem.vue";
import { Toast } from "vant";
export default {
  name: "Search",
  components: { SongItem },
  setup() {
    const store = useStore();
    // 数据
    let searchValue = ref(""); //输入框
    let hotList = ref([]); //热搜
    let resultList = ref([]); //搜索结果
    let isKeyWorkSearch = ref(false); //是否为关键字搜索
    let searchHistory = ref(JSON.parse(localStorage.getItem("history")) || []); //定义搜索历史记录
    let page = ref(1); //当前第几页

    //方法
    onMounted(async () => {
      await store.dispatch("search/gethotListData");
      hotList.value = store.state.search.hotListData.hots;
    });
    // 发起请求的方法
    const getMuse = async function () {
      //用户正常输入框输入查找结果
      await store.dispatch("search/getsearchResData", {
        type: 1,
        keywords: searchValue.value.trim(),
      });
      if (store.state.search.searchResData.songs != undefined) {
        store.state.search.searchResData.songs.forEach((obj) =>
          resultList.value.push(obj)
        );
      } else {
        resultList.value = [];
      }

      //resultList.value = store.state.search.searchResData.songs || [];
      if (!resultList.value.length) {
        Toast.setDefaultOptions({ duration: 1000 });
        Toast.setDefaultOptions("loading", { forbidClick: true });
        Toast("暂无该歌曲！");
        addHistory();
        searchValue.value = "";
      }
    };
    // 添加历史记录的方法
    const addHistory = function () {
      // 历史记录
      if (
        searchValue.value.trim() != "" &&
        !searchHistory.value.includes(searchValue.value.trim())
      ) {
        searchHistory.value.push(searchValue.value.trim());
        localStorage.setItem("history", JSON.stringify(searchHistory.value));
      }
    };
    // 点击关键字事件
    const btn = async function (str) {
      isKeyWorkSearch.value = true;
      searchValue.value = str;
      getMuse();
    };
    // 删除单个历史记录事件
    const delBtn = function (index) {
      searchHistory.value.splice(index, 1);
      localStorage.setItem("history", JSON.stringify(searchHistory.value));
    };
    // 清空历史记录事件按钮
    const clearBtn = function () {
      searchHistory.value = [];
      localStorage.setItem("history", JSON.stringify(searchHistory.value));
    };
    // 运用防抖搜索结果
    const changeIndex = debounce(async function () {
      // 如果搜索为空或者用户点击热搜进行查找结果
      if (searchValue.value.trim() == "" || isKeyWorkSearch.value) {
        if (searchValue.value.trim() == "") {
          return (resultList.value = []);
        } else {
          isKeyWorkSearch.value = false;
        }
      } else {
        // 发起请求的方法
        getMuse();
      }
      // 历史记录
      addHistory();
    }, 500);

    //watchEffect所指定的回调中用到的数据只要发生变化，则直接重新执行回调。
    watchEffect(() => {
      //要监听的值
      searchValue.value; // 搜索值
      changeIndex();
    });

    //上拉获取歌曲
    const loading = ref(false);
    const finished = ref(false);

    const onLoad = () => {
      // 加载状态结束
      page.value++;
      loading.value = false;
    };
    return {
      searchValue,
      hotList,
      btn,
      resultList,
      searchHistory,
      clearBtn,
      delBtn,
      loading,
      onLoad,
      finished,
    };
  },
};
</script>

<style lang="less" scoped>
/* 覆盖vant组件，除了less文件以外，还可以直接找到类名，直接覆盖  */
/* deep控制scoped加入的随意属性，放到选择器前面，确保能够选中组件内的标签类名 */
::v-deep .van-field__control {
  font-size: 17px;
}

/* 搜索容器的样式 */
.search_wrap {
  padding: 0.266667rem;
}

/*热门搜索文字标题样式 */
.hot_title {
  font-size: 0.32rem;
  color: #666;
}

/* 热搜词_容器 */
.hot_name_wrap {
  margin: 0.266667rem 0;
}

/* 热搜词_样式 */
.hot_item {
  display: inline-block;
  height: 0.853333rem;
  margin-right: 0.213333rem;
  margin-bottom: 0.213333rem;
  padding: 0 0.373333rem;
  font-size: 0.373333rem;
  line-height: 0.853333rem;
  color: #333;
  border-color: #d3d4da;
  border-radius: 0.853333rem;
  border: 1px solid #d3d4da;
}

/* 给单元格设置底部边框 */
.van-cell {
  border-bottom: 1px solid lightgray;
}

.van-cell[data-v-7d459965] {
  border: none;
}
::v-deep .van-cell {
  padding: 0 10px 0 0;
}
.searchKeyWork {
  .delectico {
    display: inline-block;
    padding-left: 10px;
    cursor: pointer;
  }
}
.van-cell {
  box-sizing: content-box;
}
.delete-icon {
  cursor: pointer;
}
</style>
